﻿namespace Mercury.ParticleEngine.EmitterVisualizer
{
    using System;
    using System.Windows.Media;
    using System.Windows.Shapes;

    public class VisualizerStateManager : IStateManager
    {
        public VisualizerStateManager(Int32 capacity, Rectangle[,] rectangles)
        {
            var widthHeight = Convert.ToInt32(Math.Sqrt(capacity));

            _stateBuffer = new Rectangle[capacity];

            for (int i = 0; i < capacity; i++)
            {
                _stateBuffer[i] = rectangles[i % widthHeight, i / widthHeight];
            }
        }

        private readonly Rectangle[] _stateBuffer;

        public void InitializeState(ref MetaParticleIterator iterator)
        {
        }

        public void UpdateState(ref MetaParticleIterator iterator)
        {
        }

        public unsafe void Render(ref MetaParticleIterator iterator)
        {
            var meta = iterator.First;

            do
            {
                var state = _stateBuffer[meta->Index];

                state.Fill = new SolidColorBrush(Color.FromScRgb(1f, 0f, 1f - meta->Age, 0f));
            }
            while (iterator.MoveNext(&meta));
        }
    }
}